<template>
  <base-modal
    v-if="realVisible"
    :show="realVisible"
    :title="title"
    class="advanced-search-modal"
    width="650px"
    @cancel="close"
  >
    <div class="advanced-search-modal__content">
      <div class="advanced-search-modal__view-name">
        <label for="">{{$t('component.advancedSearch.modal.name')}}</label>
        <div class="advanced-search-modal__view-name-input">
          <el-input
            v-model="viewport.viewName"
            :class="{ 'is-error': validatorError.name }"
            maxlength="10"
            :placeholder="$t('component.advancedSearch.modal.namePlaceholder')"
            @input="handleInputViewName"
          ></el-input>
          <div class="error-tip" v-if="validatorError.name">
            {{ validatorError.name }}
          </div>
        </div>
      </div>
      <div class="advanced-search-modal__form">
        <slot name="prefix">
          <!-- 自定义的固定条件 -->
        </slot>
        <slot name="searchForm">
          <advanced-search-form
            ref="searchFormRef"
            :fields="fields"
            :search-model="viewport.searchModel"
            :show-url="showUrl"
            :url="viewport.url"
            :module="module"
            :remote-method="remoteMethod"
            @change="changeForm"
          >
          </advanced-search-form>
        </slot>
      </div>
    </div>
    <template slot="footer">
      <div class="advanced-search-modal__footer">
        <div class="advanced-search-modal__footer-left">
          <el-checkbox
            v-model="viewport.visibleType"
            :true-label="1"
            :false-label="0"
          >
            {{$t('component.advancedSearch.modal.fullyVisible')}}
          </el-checkbox>
        </div>
        <div class="advanced-search-modal__footer-right">
          <el-button type="plain-third" @click="close">{{$t('common.base.cancel')}}</el-button>
          <el-button type="primary" :loading="loading" @click="handleSave">
            {{$t('common.base.save')}}
          </el-button>
          <!-- <el-button @click="clearField">清空筛选项</el-button> -->
        </div>
      </div>
    </template>
  </base-modal>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  watchEffect,
  computed,
} from 'vue';
import AdvancedSearchForm from './AdvancedSearchForm.vue';
import { saveViewport, getViewUrl } from '@src/api/Viewport';
import { toast } from '@src/util/platform';
import i18n from '@src/locales';

const nameErrorTip = {
  empty: i18n.t('component.advancedSearch.modal.namePlaceholder'),
};

export default defineComponent({
  name: 'AdvancedSearchModal',
  components: {
    AdvancedSearchForm,
  },
  props: {
    // 显示
    visible: {
      type: Boolean,
      default: false,
    },
    // 字段列表
    fields: {
      type: Array,
      default: () => [],
    },
    // 远程搜索接口列表
    remoteMethod: {
      type: Object,
      default: () => ({}),
    },
    // 模块
    module: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default: () => null,
    },
    // 点击保存之前
    beforeSave: {
      type: Function,
      default: null,
    },
    allowEmpty: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:value'],
  setup(props, { emit }) {
    // 是否显示
    const realVisible = ref(false);
    // 表单ref
    const searchFormRef = ref();
    // 视图信息
    const viewport = ref(null);
    // 是否编辑模式
    const isEdit = ref(false);
    // 是否显示访问地址
    const showUrl = ref(false);
    // modal 标题
    const title = computed(() => (isEdit.value ? i18n.t('component.advancedSearch.modal.editTitle') : i18n.t('component.advancedSearch.modal.createTitle')));
    // loading
    const loading = ref(false);

    const validatorError = ref({
      name: '',
    });

    // 初始化视图数据
    async function initViewport(_v = {}) {
      viewport.value = {
        viewName: '', // 视图名称
        visibleType: 0,
        url: '',
        ..._v,
      };
      isEdit.value = !!viewport.value.viewId;
      // 新建视图时调接口获取访问地址
      showUrl.value = ['task', 'customer', 'product', 'taskPool'].includes(props.module)
      if (!isEdit.value && showUrl.value) {
        const res = await getViewUrl({module: props.module})
        viewport.value.url = res.url || viewport.value.url
      }
    }

    // 输入视图名称 过滤空格
    function handleInputViewName(value) {
      viewport.value.viewName = value.trim();
      validatorError.value.name =
        viewport.value.viewName === '' ? nameErrorTip.empty : '';
    }

    // 表单change
    function changeForm() {
      emit('change');
    }

    // 点击保存
    async function handleSave() {
      const conditions = searchFormRef.value.getSearchList();
      const searchModel = conditions.map(({ fieldName, operator, value, timeType }) => ({
        fieldName,
        operator,
        value,
        timeType,
      }));
      if (!viewport.value.viewName)
        return (validatorError.value.name = nameErrorTip.empty);
      if (!props.allowEmpty && !searchModel.length)
        return toast(i18n.t('component.advancedSearch.modal.saveTip.noCondition'), 'warning');
      if (props.beforeSave) {
        // 编辑视图时外部固定条件使用视图本来的数据
        const otherSearchModel = props.beforeSave(isEdit.value ? viewport.value : '');
        searchModel.unshift(...otherSearchModel);
      }
      try {
        loading.value = true;
        const res = await saveViewport({
          ...viewport.value,
          module: props.module,
          searchModel,
        });
        toast(i18n.t('common.base.saveSuccess'));
        close();
        emit('save', res);
      } catch (error) {
        toast(i18n.t('common.base.saveFail'), 'error');
        console.error('save viewport error: ', error);
      } finally {
        loading.value = false;
      }
    }

    // 清除表单值
    function clearField() {
      searchFormRef.value?.clear();
    }

    /**
     * 打开
     * @param _viewport null -> 新建
     * @param isEdit 是否编辑模式
     */
    function open(_viewport = {}) {
      initViewport(_viewport);
      realVisible.value = true;
      emit('update:visible', true);
    }

    // 关闭modal
    function close() {
      realVisible.value = false;
      emit('update:visible', false);
    }

    {
      // 改变 modal 显示状态
      watchEffect(() => (realVisible.value = props.visible));
      // 改变内容
      watch(
        () => props.data,
        _viewport => {
          initViewport(_viewport);
        }
      );
    }

    return {
      realVisible,
      title,
      searchFormRef,
      isEdit,
      showUrl,
      viewport,
      loading,
      validatorError,

      handleInputViewName,
      open,
      close,
      changeForm,
      handleSave,
      clearField,
    };
  },
});
</script>

<style lang="scss">
.advanced-search-modal {
  padding-top: 50px;
  align-items: flex-start;
  padding: 0;
  user-select: none;
}
.advanced-search-modal__content {
  padding: 24px 30px;
  user-select: none;
  .advanced-search-modal__view-name {
    position: relative;
    margin-bottom: 12px;
    display: flex;
    align-items: flex-start;
    label {
      margin-right: 10px;
      line-height: 32px;
      width: 70px;
      white-space: nowrap;
    }

    .el-input {
      width: 360px;
      &.is-error input {
        border-color: $color-danger;
      }
    }
    &::before {
      content: '*';
      color: $color-danger;
      position: absolute;
      left: -8px;
      top: 6px;
    }
  }

  .error-tip {
    padding: 4px 0;
    font-size: 12px;
    color: $color-danger;
  }
}
.advanced-search-modal__footer {
  padding: 5px 10px; // modal footer 自带 10px 20px
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .advanced-search-modal__footer-left {
    display: flex;
    align-items: center;
  }

  .advanced-search-modal__footer-right {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
